package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WeMediaThreadLocalUnit;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl3 extends ServiceImpl<WmNewsMapper, WmNews> {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 文章列表查询
     *
     * @param dto
     * @return
     */
    public ResponseResult getList(WmNewsPageDto dto) {
        //0、参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //0.1、分页参数校验
        dto.checkParam();
        //1、分页查询
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        //1.1、标题关键字模糊查询
        lqw.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //1.2、频道id精确查询
        lqw.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //1.3、状态精确查询
        lqw.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //1.4、时间范围查询
        lqw.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        //1.5、倒序发布时间
        lqw.orderByDesc(WmNews::getPublishTime);
        //1.6、分页参数设置
        IPage iPage = new Page(dto.getPage(), dto.getSize());
        //1.7、查询
        page(iPage, lqw);
        //2、返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        pageResponseResult.setData(iPage.getRecords());
        return pageResponseResult;
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    public ResponseResult submit(WmNewsDto dto) {
        //1、参数校验
        if (dto == null || dto.getContent() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、保存或修改文章
        // 拷贝属性
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // images type
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            wmNews.setImages(StringUtils.join(dto.getImages(), ","));
        }
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 保存到文章表
        saveOrUpdateWmNews(dto, wmNews);

        //3、判断是不是草稿
        //3.1、草稿直接返回结束方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //4、不是草稿
        //4.1、先提取文章内容图片
        List<String> materials = extractImage(wmNews.getContent());
        //4.2、处理文章内容图片与素材的关系
        saveRelationInfoContent(materials, wmNews.getId());
        //4.3、处理文章封面图片与素材的关系
        saveRelationInfoForCover(materials,dto,wmNews);
        //5、响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 处理文章封面图片与素材的关系
     * 功能1：如果前端传过来的是自动 -1
     *  1：文章图片数量 1 2  单图 type 1
     *  2：文章图片数量 》= 3  多图 type 3
     *  3：文章图片数量 0  无图 type 0
     * 功能二： 保存封面图片到数据库
     * @param materials
     * @param dto
     * @param wmNews
     */
    private void saveRelationInfoForCover(List<String> materials, WmNewsDto dto, WmNews wmNews) {
        //先获取前端传过来文章封面图片信息
        List<String> images = dto.getImages();
        //若为自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //单图情况
            if (materials.size() > 0 && materials.size() < 3) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (materials.size() > 2) {
                //多图
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //判断并存入数据库
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images,","));
                updateById(wmNews);
            }
        }
        if (images != null && images.size() > 0) {
            //保存封面图片与素材关系  不用再存文章表了 之前第一步已经存过了
            saveRelationInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 处理文章内容图片和素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelationInfoContent(List<String> materials, Integer newsId) {
        //保存  文章内容图片 0
        saveRelationInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存关系到数据库 WmNewsMaterial
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelationInfo(List<String> materials, Integer newsId, Short type) {
        //判断图片url集合是否有限
        if (materials != null && materials.size() > 0) {
            //查询获取素材对象
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            //判断素材（数据库查出来的）的数量和前端传过来的是否相等 防止有脏数据
            if (wmMaterials.size() != materials.size()) {
                System.out.println(wmMaterials.size());
                System.out.println(materials.size());
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFEENCE_FAIL); //事务 数据回滚
            }
            //通过对象获取id
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //保存
            wmNewsMaterialMapper.saveRelations(ids,newsId,type);
        }
    }

    /**
     * 提取文章内容中图片
     *
     * @param content
     * @return
     */
    private List<String> extractImage(String content) {
        ArrayList<String> materials = new ArrayList<>();
        //解析
        JSONArray jsonArray = JSON.parseArray(content);
        //遍历，
        for (Object json : jsonArray) {
            //转成json对象
            JSONObject jsonObject = JSON.parseObject(json.toString());
            if (jsonObject.get("type").equals("image")) {
                String url = jsonObject.get("value").toString();
                materials.add(url);
            }
        }
        return materials;
    }

    /**
     * 新增/修改文章
     *
     * @param dto
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNewsDto dto, WmNews wmNews) {
        //完善公用属性
        wmNews.setSubmitedTime(new Date());
        //判断id
        if (dto.getId() == null) {
            //新增 继续完善属性
            wmNews.setCreatedTime(new Date());
            wmNews.setEnable((short) 1);//默认上架
            wmNews.setUserId(WeMediaThreadLocalUnit.get());
            save(wmNews);
        } else {
            // 修改
            // 先删除原有关系表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }
}
